package com.atguigu.servicevod.service.Impl;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.atguigu.servicebase.handler.CustomException;
import com.atguigu.servicevod.constant.ConstantPropertiesUtil;
import com.atguigu.servicevod.service.VideoService;
import com.atguigu.servicevod.util.InitVideoClientUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
@Service
public class VideoServiceImpl implements VideoService {


	@Override
	public String uploadVideo(MultipartFile file) {
		try {

			InputStream inputStream = file.getInputStream();
			String originalFilename = file.getOriginalFilename();
			//上传之后显示的名称
			String title = originalFilename.substring(0,originalFilename.lastIndexOf("."));
			return testUploadStream(title,originalFilename,inputStream);

		} catch (IOException e) {
			e.printStackTrace();
		}
		return "上传失败哦";
	}

	private static String testUploadStream(String title, String fileName, InputStream inputStream) {
		UploadStreamRequest request = new UploadStreamRequest("LTAI5tJD2dVWiz8bKvQbekvU", "Ol881FC2M2Bo7F7eu1y4A0VOxdLY3L", title, fileName, inputStream);
		UploadVideoImpl uploader = new UploadVideoImpl();
		UploadStreamResponse response = uploader.uploadStream(request);
		System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
		if (response.isSuccess()) {
			return response.getVideoId();
		} else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
			return "上传失败";

		}
	}

	@Override
	public void removeVideo(String videoId) {

		try {
			DefaultAcsClient defaultAcsClient = InitVideoClientUtil.initVodClient(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET);
			DeleteVideoRequest request=new DeleteVideoRequest();
			request.setVideoIds(videoId);
			//调用初始化对象的方法实现删除
			defaultAcsClient.getAcsResponse(request);

		} catch (ClientException e) {
			e.printStackTrace();
			throw new CustomException(20001,"删除视频失败");
		}

	}

}
